<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="PersonId_FormItem" prop="PersonId" label="员工">
							<el-select v-model="searchData.PersonId" :data="stateData.AllSysPersons" clearable>
								<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="AttendanceResult_FormItem" prop="AttendanceResult">
							<template #label>
								<WtmLabelTooltip label="出勤结果" tooltip="考勤计算后的出勤结果状态" />
							</template>
							<el-select v-model="searchData.AttendanceResult" clearable>
								<el-option key="未计算" value="未计算" label="未计算"></el-option>
								<el-option key="正常" value="正常" label="正常"></el-option>
								<el-option key="迟到" value="迟到" label="迟到"></el-option>
								<el-option key="早退" value="早退" label="早退"></el-option>
								<el-option key="迟到且早退" value="迟到且早退" label="迟到且早退"></el-option>
								<el-option key="缺卡" value="缺卡" label="缺卡"></el-option>
								<el-option key="旷工" value="旷工" label="旷工"></el-option
							></el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="IsAbnormal_FormItem" prop="IsAbnormal">
							<template #label>
								<WtmLabelTooltip label="是否异常" tooltip="是否存在考勤异常（迟到、早退、缺卡、旷工等）" />
							</template>
							<el-select v-model="searchData.IsAbnormal" clearable>
								<el-option :key="1" :value="true" :label="$t('message._system.common.vm.tips_bool_true')"></el-option>
								<el-option :key="0" :value="false" :label="$t('message._system.common.vm.tips_bool_false')"></el-option>
								></el-select
							>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="AttendanceShiftId_FormItem" prop="AttendanceShiftId" label="班次">
							<el-select v-model="searchData.AttendanceShiftId" :data="stateData.AllSysAttendanceShifts" clearable>
								<el-option v-for="item in stateData.AllSysAttendanceShifts" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
							></el-select>
						</el-form-item>
					</el-col>

					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ShiftType_FormItem" prop="ShiftType">
								<template #label>
									<WtmLabelTooltip label="班次类型" tooltip="班次类型：正常上班、请假、调休、替班、换班等" />
								</template>
								<el-select v-model="searchData.ShiftType" clearable>
									<el-option key="正常上班" value="正常上班" label="正常上班"></el-option>
									<el-option key="请假" value="请假" label="请假"></el-option>
									<el-option key="调休" value="调休" label="调休"></el-option>
									<el-option key="替班" value="替班" label="替班"></el-option>
									<el-option key="换班" value="换班" label="换班"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="ScheduleType_FormItem" prop="ScheduleType">
								<template #label>
									<WtmLabelTooltip label="排班方式" tooltip="排班方式：自动排班（系统生成）、人工排班（手动调整）" />
								</template>
								<el-select v-model="searchData.ScheduleType" clearable>
									<el-option key="自动排班" value="自动排班" label="自动排班"></el-option>
									<el-option key="人工排班" value="人工排班" label="人工排班"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Status_FormItem" prop="Status">
								<template #label>
									<WtmLabelTooltip label="班次状态" tooltip="班次状态：正常、取消、暂停等" />
								</template>
								<el-select v-model="searchData.Status" clearable>
									<el-option key="正常" value="正常" label="正常"></el-option>
									<el-option key="取消" value="取消" label="取消"></el-option>
									<el-option key="暂停" value="暂停" label="暂停"></el-option
								></el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="SubstitutePersonId_FormItem" prop="SubstitutePersonId" label="替班人员">
								<el-select v-model="searchData.SubstitutePersonId" :data="stateData.AllSysPersons" clearable>
									<el-option v-for="item in stateData.AllSysPersons" :key="item.Value" :value="item.Value" :label="item.Text"></el-option
								></el-select>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysAttendanceRecord/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceRecord/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceRecord/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/SysAttendanceRecord/SysAttendanceRecordExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>
		<div class="main-content-layout">
			<div class="left-panel">
				<WtmDeptTree ref="deptTreeRef" title="筛选部门" @node-click="handleDeptNodeClick" :showCompanySelector="false" />
			</div>
			<div class="right-panel">
				<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
					<template #operation>
						<el-table-column :label="$t('message._system.common.vm.operate')" min-width="180" align="center" class-name="operation-column">
							<template v-slot="scope">
								<div class="operation-container">
									<WtmButton
										v-auth="'/api/SysAttendanceRecord/Edit'"
										:is-text="true"
										icon="fa fa-pencil-square"
										type="warning"
										:button-text="$t('message._system.common.vm.edit')"
										@click="OnEditRowClick(scope.row)"
									/>
									<WtmButton
										v-auth="'/api/SysAttendanceRecord/{id}'"
										:is-text="true"
										icon="fa fa-info-circle"
										type="info"
										:button-text="$t('message._system.common.vm.detail')"
										@click="OnDetailsRowClick(scope.row)"
									/>
									<WtmButton
										v-auth="'/api/SysAttendanceRecord/BatchDelete'"
										icon="fa fa-trash"
										type="danger"
										:button-text="$t('message._system.common.vm.delete')"
										:confirm="$t('message._system.common.vm.deletetip')"
										:is-text="true"
										@click="onDelete(scope.row)"
									/>
								</div>
							</template>
						</el-table-column>
					</template>
				</WtmTable>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="自由排班copy;true;HengTong.Areas.Hr.Controllers">
import ElMessage from 'element-plus/es/components/message/index';
import { defineAsyncComponent, reactive, ref, getCurrentInstance, onMounted, computed } from 'vue';
import { SysAttendanceRecordApi as api } from '/@/views/hr/sysattendancerecord/api';
import { ISysAttendanceRecordView, ISysAttendanceRecordQuery } from '/@/views/hr/sysattendancerecord/api/interface';
import other from '/@/utils/other';
import { IViewModel, ISysSelectType } from '/@/types/common';

const ci = getCurrentInstance() as any;
const loading = ref(false);
const CreateDialog = defineAsyncComponent(() => import('./create.vue'));
const EditDialog = defineAsyncComponent(() => import('./edit.vue'));
const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const ImportDialog = defineAsyncComponent(() => import('./import.vue'));

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysAttendanceRecordQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysPersons: [] as ISysSelectType[],
	AllSysAttendanceShifts: [] as ISysSelectType[],
});

const searchData = ref<ISysAttendanceRecordQuery>({
	PersonId: null,
	AttendanceShiftId: null,
	ShiftType: null,
	ScheduleType: null,
	Status: null,
	SubstitutePersonId: null,
	AttendanceResult: null,
	IsAbnormal: null,
});

// 定义变量内容
const tableRef = ref();
const tableData = ref({
	// 列表数据（必传）s
	data: [],
	// 表头内容（必传，注意格式）
	header: [
		{ title: '员工', key: 'PersonName', type: 'text', isCheck: true },
		{ title: '班次', key: 'AttendanceShiftName', type: 'text', isCheck: true },
		{
			title: '出勤结果',
			key: 'AttendanceResult',
			type: 'tag',
			isCheck: true,
			tagType: (row: ISysAttendanceRecordView) => {
				const statusMap: Record<string, string> = {
					未计算: 'info',
					正常: 'success',
					迟到: 'warning',
					早退: 'warning',
					迟到且早退: 'danger',
					缺卡: 'danger',
					旷工: 'danger',
				};
				return statusMap[row.AttendanceResult || ''] || 'info';
			},
		},
		{ title: '是否异常', key: 'IsAbnormal', type: 'switch', isCheck: true },
		{ title: '班次类型', key: 'ShiftType', type: 'text', isCheck: true },
		{ title: '班次状态', key: 'Status', type: 'text', isCheck: true },
		{ title: '有效工时(分钟)', key: 'WorkMinutes', type: 'text', isCheck: true },
		{ title: '迟到时长(分钟)', key: 'LateMinutes', type: 'text', isCheck: true },
		{ title: '早退时长(分钟)', key: 'EarlyLeaveMinutes', type: 'text', isCheck: true },
		{ title: '缺卡次数', key: 'MissingPunchCount', type: 'text', isCheck: true },
		{ title: '替班人员', key: 'SubstitutePersonName', type: 'text', isCheck: true },
		{ title: '排班方式', key: 'ScheduleType', type: 'text', isCheck: true },
		{ title: '备注说明', key: 'Remark', type: 'text', isCheck: true },
	],
	// 配置项（必传）
	config: {
		total: 0, // 列表总数
		loading: true, // loading 加载
		isSerialNo: true, // 是否显示表格序号
		isSelection: true, // 是否显示表格多选
		isOperate: props.isDisabled, // 是否显示表格操作栏
	},
});
// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		other.setFormError(ci, error);
	}
};
const OnCreateClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.add'), CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysAttendanceRecordView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.edit'), EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysAttendanceRecordView) => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.detail'), DetailsDialog, row, getTableData);
};

// 删除
const onDelete = (row: ISysAttendanceRecordView) => {
	const ids = [row.ID] as (string | number)[];
	api()
		.delete(ids)
		.then(() => {
			getTableData();
		});
};

//批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysAttendanceRecordView) => x.ID) as (string | number)[];
	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			// 先清除选择状态
			tableRef.value?.clearSelection();
			// 再重新获取数据
			getTableData();
		} catch (error) {
			ElMessage.error(ci.proxy.$t('message._system.common.vm.error'));
		}
	} else {
		ElMessage.error(ci.proxy.$t('message._system.common.vm.check'));
	}
};
// 添加计算属性判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

const OnImportClick = () => {
	other.openDialog(ci.proxy.$t('message._system.common.vm.import'), ImportDialog, null, getTableData);
};

const onExport = () => {
	const selected = tableRef.value.getSelectedRows();
	if (selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 页面加载时
onMounted(() => {
	loading.value = true;
	const promises: Promise<any>[] = [
		other.getSelectList('/api/SysAttendanceRecord/GetSysPersons', [], false).then((x) => (stateData.AllSysPersons = x)),
		other.getSelectList('/api/SysAttendanceRecord/GetSysAttendanceShifts', [], false).then((x) => (stateData.AllSysAttendanceShifts = x)),

		getTableData(),
	];
	Promise.allSettled(promises).finally(() => {
		loading.value = false;
	});
});
</script>
